package com.luckcoder.relax.games.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.luckcoder.relax.games.domain.bo.RelaxGameConfigBo;
import com.luckcoder.relax.games.domain.bo.RelaxUserGameRecordBo;
import com.luckcoder.relax.games.domain.bo.RelaxGameRecordDetailBo;
import com.luckcoder.relax.games.domain.bo.RelaxEmojiStatisticsBo;
import com.luckcoder.relax.games.domain.vo.MiniappGameVo;
import com.luckcoder.relax.games.domain.vo.RelaxGameConfigVo;
import com.luckcoder.relax.games.domain.vo.RelaxEmojiStatisticsVo;
import com.luckcoder.relax.games.domain.vo.RelaxUserGameRecordVo;
import com.luckcoder.relax.games.domain.dto.GameFinishData;
import com.luckcoder.relax.games.domain.dto.UserGameStats;
import com.luckcoder.relax.games.domain.dto.GlobalGameStats;
import com.luckcoder.relax.games.domain.dto.EmojiRankingItem;
import com.luckcoder.relax.games.service.IRelaxGameConfigService;
import com.luckcoder.relax.games.service.IRelaxUserGameRecordService;
import com.luckcoder.relax.games.service.IRelaxGameRecordDetailService;
import com.luckcoder.relax.games.service.IRelaxEmojiStatisticsService;
import com.luckcoder.relax.games.service.IMiniappGameService;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 小程序游戏服务实现
 *
 * @author zhanghao
 * @date 2025-09-10
 */
@RequiredArgsConstructor
@Service
public class MiniappGameServiceImpl implements IMiniappGameService {
    
    private final IRelaxGameConfigService relaxGameConfigService;
    private final IRelaxUserGameRecordService relaxUserGameRecordService;
    private final IRelaxGameRecordDetailService relaxGameRecordDetailService;
    private final IRelaxEmojiStatisticsService relaxEmojiStatisticsService;
    
    /**
     * 游戏颜色配置
     */
    private static final Map<String, String> GAME_COLORS = new HashMap<>();
    
    static {
        GAME_COLORS.put("bubble_pop", "#6c5ce7");
        GAME_COLORS.put("emoji_eliminate", "#fd79a8");
        GAME_COLORS.put("breathe", "#00b894");
        GAME_COLORS.put("color", "#fd79a8");
        GAME_COLORS.put("memory", "#e17055");
        GAME_COLORS.put("draw", "#fdcb6e");
        GAME_COLORS.put("puzzle", "#a29bfe");
    }
    
    /**
     * 难度等级配置
     */
    private static final Map<String, String> DIFFICULTY_LEVELS = new HashMap<>();
    
    static {
        DIFFICULTY_LEVELS.put("casual", "简单");
        DIFFICULTY_LEVELS.put("strategy", "中等");
        DIFFICULTY_LEVELS.put("action", "困难");
        DIFFICULTY_LEVELS.put("puzzle", "困难");
    }
    
    @Override
    public List<MiniappGameVo> getAvailableGames() {
        // 查询启用的游戏配置
        RelaxGameConfigBo queryBo = new RelaxGameConfigBo();
        queryBo.setStatus("0"); // 正常状态
        queryBo.setIsEnabled("1"); // 启用状态
        
        List<RelaxGameConfigVo> gameConfigs = relaxGameConfigService.queryList(queryBo);
        
        return gameConfigs.stream()
            .map(this::convertToMiniappVo)
            .sorted((a, b) -> Integer.compare(
                a.getSortOrder() != null ? a.getSortOrder() : 999,
                b.getSortOrder() != null ? b.getSortOrder() : 999
            ))
            .collect(Collectors.toList());
    }
    
    /**
     * 转换为小程序VO对象
     */
    private MiniappGameVo convertToMiniappVo(RelaxGameConfigVo config) {
        MiniappGameVo vo = new MiniappGameVo();
        BeanUtil.copyProperties(config, vo);
        
        // 设置游戏颜色
        String gameColor = GAME_COLORS.getOrDefault(config.getGameCode(), "#6c5ce7");
        vo.setGameColor(gameColor);
        
        // 设置难度等级
        String difficulty = DIFFICULTY_LEVELS.getOrDefault(config.getGameCategory(), "简单");
        vo.setDifficulty(difficulty);
        
        // 设置游玩次数（从数据库获取真实数据）
        vo.setPlayCount(generatePlayCount(config.getGameCode()));
        
        // 判断是否可用
        boolean available = "0".equals(config.getStatus()) && "1".equals(config.getIsEnabled());
        vo.setAvailable(available);
        
        // 处理游戏路径，确保以/pages开头
        String gamePath = config.getGamePath();
        if (StrUtil.isNotBlank(gamePath) && !gamePath.startsWith("/pages")) {
            gamePath = "/pages/relax/game/" + config.getGameCode() + "/index";
        }
        vo.setGamePath(gamePath);
        
        return vo;
    }
    
    /**
     * 获取游玩次数（从数据库获取真实数据）
     */
    private String generatePlayCount(String gameCode) {
        try {
            Long playCount = relaxUserGameRecordService.countByGameCode(gameCode);
            return formatPlayCount(playCount);
        } catch (Exception e) {
            // 如果查询失败，返回默认值
            return "0";
        }
    }
    
    /**
     * 格式化游玩次数显示
     */
    private String formatPlayCount(Long count) {
        if (count == null || count == 0) {
            return "0";
        }
        
        if (count >= 10000) {
            double wan = count / 10000.0;
            if (wan >= 10) {
                return String.format("%.0f万", wan);
            } else {
                return String.format("%.1f万", wan);
            }
        } else if (count >= 1000) {
            double qian = count / 1000.0;
            return String.format("%.1fk", qian);
        } else {
            return count.toString();
        }
    }
    
    @Override
    public Long startGame(String gameCode) {
        // 获取当前用户ID
        Long userId = LoginHelper.getUserId();
        
        // 根据游戏编码查询游戏配置
        RelaxGameConfigBo queryBo = new RelaxGameConfigBo();
        queryBo.setGameCode(gameCode);
        queryBo.setStatus("0"); // 正常状态
        queryBo.setIsEnabled("1"); // 启用状态
        
        List<RelaxGameConfigVo> gameConfigs = relaxGameConfigService.queryList(queryBo);
        if (gameConfigs.isEmpty()) {
            throw new RuntimeException("游戏不存在或未启用: " + gameCode);
        }
        
        RelaxGameConfigVo gameConfig = gameConfigs.get(0);
        
        // 创建游戏记录
        RelaxUserGameRecordBo recordBo = new RelaxUserGameRecordBo();
        recordBo.setUserId(userId);
        recordBo.setGameId(gameConfig.getGameId());
        recordBo.setGameCode(gameCode);
        recordBo.setScore(0L); // 初始分数为0
        recordBo.setPlayTime(0L); // 初始游戏时长为0
        recordBo.setGameLevel(1L); // 默认等级为1
        recordBo.setGameMode("normal"); // 默认普通模式
        recordBo.setGameResult("started"); // 游戏开始状态
        recordBo.setEliminatedCount(0L); // 初始消灭数量为0
        recordBo.setPlayDate(Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant()));
        
        // 保存游戏记录
        boolean success = relaxUserGameRecordService.insertByBo(recordBo);
        if (!success) {
            throw new RuntimeException("创建游戏记录失败");
        }
        
        return recordBo.getRecordId();
    }
    
    @Override
    public void finishGame(Long recordId, GameFinishData gameFinishData) {
        // 获取当前用户ID
        Long userId = LoginHelper.getUserId();
        
        // 更新游戏记录基本信息
        RelaxUserGameRecordBo recordBo = new RelaxUserGameRecordBo();
        recordBo.setRecordId(recordId);
        recordBo.setScore(gameFinishData.getFinalScore());
        recordBo.setPlayTime(gameFinishData.getPlayTime());
        recordBo.setGameResult(gameFinishData.getGameResult());
        recordBo.setGameMode(gameFinishData.getGameMode());
        recordBo.setEliminatedCount(gameFinishData.getTotalEliminatedCount());
        recordBo.setExtraData(gameFinishData.getExtraData());
        
        // 更新游戏记录
        relaxUserGameRecordService.updateByBo(recordBo);
        
        // 批量保存游戏详细数据和统计数据
        if (gameFinishData.getEmojiDetails() != null && !gameFinishData.getEmojiDetails().isEmpty()) {
            batchSaveGameData(recordId, userId, gameFinishData.getGameCode(), gameFinishData.getEmojiDetails());
        }
    }
    
    /**
     * 保存游戏记录详情
     */
    private void saveGameRecordDetail(Long recordId, Long userId, String gameCode, 
                                     GameFinishData.EmojiEliminateDetail detail) {
        RelaxGameRecordDetailBo detailBo = new RelaxGameRecordDetailBo();
        detailBo.setRecordId(recordId);
        detailBo.setUserId(userId);
        detailBo.setGameCode(gameCode);
        detailBo.setEmojiUnicode(detail.getEmojiUnicode());
        detailBo.setEmojiChar(detail.getEmojiChar());
        detailBo.setEliminatedCount(detail.getEliminatedCount());
        
        // 设置消灭时间（使用最后消灭时间）
        if (detail.getLastEliminatedTime() != null) {
            detailBo.setEliminatedTime(new Date(detail.getLastEliminatedTime()));
        }
        
        relaxGameRecordDetailService.insertByBo(detailBo);
    }
    
    /**
     * 更新emoji统计数据
     */
    private void updateEmojiStatistics(Long userId, GameFinishData.EmojiEliminateDetail detail) {
        // 查询是否已存在该用户和emoji的统计记录
        RelaxEmojiStatisticsBo queryBo = new RelaxEmojiStatisticsBo();
        queryBo.setUserId(userId);
        queryBo.setEmojiUnicode(detail.getEmojiUnicode());
        
        List<RelaxEmojiStatisticsVo> existingStats = relaxEmojiStatisticsService.queryList(queryBo);
        
        if (existingStats.isEmpty()) {
            // 创建新的统计记录
            RelaxEmojiStatisticsBo statBo = new RelaxEmojiStatisticsBo();
            statBo.setUserId(userId);
            statBo.setEmojiUnicode(detail.getEmojiUnicode());
            statBo.setEmojiChar(detail.getEmojiChar());
            statBo.setEliminatedCount(detail.getEliminatedCount());
            
            if (detail.getFirstEliminatedTime() != null) {
                statBo.setFirstEliminated(new Date(detail.getFirstEliminatedTime()));
            }
            if (detail.getLastEliminatedTime() != null) {
                statBo.setLastEliminated(new Date(detail.getLastEliminatedTime()));
            }
            
            relaxEmojiStatisticsService.insertByBo(statBo);
        } else {
            // 更新现有统计记录
            RelaxEmojiStatisticsVo existingStat = existingStats.get(0);
            RelaxEmojiStatisticsBo updateBo = new RelaxEmojiStatisticsBo();
            updateBo.setStatId(existingStat.getStatId());
            updateBo.setEliminatedCount(existingStat.getEliminatedCount() + detail.getEliminatedCount());
            
            if (detail.getLastEliminatedTime() != null) {
                updateBo.setLastEliminated(new Date(detail.getLastEliminatedTime()));
            }
            
            relaxEmojiStatisticsService.updateByBo(updateBo);
        }
    }
    
    @Override
    public UserGameStats getUserGameStats(String gameCode) {
        Long userId = LoginHelper.getUserId();
        UserGameStats stats = new UserGameStats();
        stats.setGameCode(gameCode);
        
        try {
            // 查询基本游戏统计数据
            populateBasicGameStats(stats, userId, gameCode);
            
            // 查询个人emoji统计数据
            populatePersonalEmojiStats(stats, userId);
            
            // 查询近期游戏记录
            populateRecentGameRecords(stats, userId, gameCode);
            
        } catch (Exception e) {
            System.err.println("查询用户游戏统计失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        return stats;
    }
    
    /**
     * 填充基本游戏统计数据
     */
    private void populateBasicGameStats(UserGameStats stats, Long userId, String gameCode) {
        RelaxUserGameRecordBo queryBo = new RelaxUserGameRecordBo();
        queryBo.setUserId(userId);
        queryBo.setGameCode(gameCode);
        
        List<RelaxUserGameRecordVo> records = relaxUserGameRecordService.queryList(queryBo);
        
        if (records.isEmpty()) {
            // 设置默认值
            stats.setTotalPlayCount(0);
            stats.setBestScore(0L);
            stats.setTotalScore(0L);
            stats.setAvgScore(0.0);
            stats.setTotalPlayTime(0);
            stats.setAvgPlayTime(0.0);
            stats.setTotalEliminatedCount(0);
            stats.setMaxCombo(0);
            stats.setCompletedCount(0);
            stats.setTimeoutCount(0);
            stats.setQuitCount(0);
            return;
        }
        
        // 计算基本统计数据
        stats.setTotalPlayCount(records.size());
        
        long totalScore = 0;
        long totalPlayTime = 0;
        long totalEliminated = 0;
        long bestScore = 0;
        int maxCombo = 0;
        int completedCount = 0;
        int timeoutCount = 0;
        int quitCount = 0;
        
        LocalDateTime firstPlayTime = null;
        LocalDateTime lastPlayTime = null;
        
        for (RelaxUserGameRecordVo record : records) {
            // 累计数据
            if (record.getScore() != null) {
                totalScore += record.getScore();
                if (record.getScore() > bestScore) {
                    bestScore = record.getScore();
                }
            }
            
            if (record.getPlayTime() != null) {
                totalPlayTime += record.getPlayTime();
            }
            
            if (record.getEliminatedCount() != null) {
                totalEliminated += record.getEliminatedCount();
            }
            
            // 解析extraData获取连击数据
            if (record.getExtraData() != null) {
                try {
                    // 简单解析JSON字符串获取maxCombo
                    String extraData = record.getExtraData();
                    if (extraData.contains("\"maxCombo\"")) {
                        // 提取maxCombo值（简单解析）
                        int comboStart = extraData.indexOf("\"maxCombo\":") + 11;
                        int comboEnd = extraData.indexOf(",", comboStart);
                        if (comboEnd == -1) comboEnd = extraData.indexOf("}", comboStart);
                        
                        if (comboEnd > comboStart) {
                            String comboStr = extraData.substring(comboStart, comboEnd).trim();
                            int recordMaxCombo = Integer.parseInt(comboStr);
                            if (recordMaxCombo > maxCombo) {
                                maxCombo = recordMaxCombo;
                            }
                        }
                    }
                } catch (Exception e) {
                    // 忽略解析错误
                }
            }
            
            // 统计游戏结果
            String gameResult = record.getGameResult();
            if ("completed".equals(gameResult)) {
                completedCount++;
            } else if ("timeout".equals(gameResult)) {
                timeoutCount++;
            } else if ("quit".equals(gameResult)) {
                quitCount++;
            }
            
            // 记录时间范围
            if (record.getCreateTime() != null) {
                LocalDateTime createTime = record.getCreateTime().toInstant()
                    .atZone(ZoneId.systemDefault()).toLocalDateTime();
                
                if (firstPlayTime == null || createTime.isBefore(firstPlayTime)) {
                    firstPlayTime = createTime;
                }
                if (lastPlayTime == null || createTime.isAfter(lastPlayTime)) {
                    lastPlayTime = createTime;
                }
            }
        }
        
        // 设置统计结果
        stats.setBestScore(bestScore);
        stats.setTotalScore(totalScore);
        stats.setAvgScore(stats.getTotalPlayCount() > 0 ? (double) totalScore / stats.getTotalPlayCount() : 0.0);
        stats.setTotalPlayTime((int) totalPlayTime);
        stats.setAvgPlayTime(stats.getTotalPlayCount() > 0 ? (double) totalPlayTime / stats.getTotalPlayCount() : 0.0);
        stats.setTotalEliminatedCount((int) totalEliminated);
        stats.setMaxCombo(maxCombo);
        stats.setCompletedCount(completedCount);
        stats.setTimeoutCount(timeoutCount);
        stats.setQuitCount(quitCount);
        stats.setFirstPlayTime(firstPlayTime);
        stats.setLastPlayTime(lastPlayTime);
    }
    
    /**
     * 填充个人emoji统计数据
     */
    private void populatePersonalEmojiStats(UserGameStats stats, Long userId) {
        RelaxEmojiStatisticsBo queryBo = new RelaxEmojiStatisticsBo();
        queryBo.setUserId(userId);
        
        List<RelaxEmojiStatisticsVo> emojiStats = relaxEmojiStatisticsService.queryList(queryBo);
        
        // 按消灭次数排序，取前10名
        List<UserGameStats.PersonalEmojiStat> topEmojiStats = emojiStats.stream()
            .sorted((a, b) -> Long.compare(b.getEliminatedCount(), a.getEliminatedCount()))
            .limit(10)
            .map(stat -> {
                UserGameStats.PersonalEmojiStat personalStat = new UserGameStats.PersonalEmojiStat();
                personalStat.setEmojiChar(stat.getEmojiChar());
                personalStat.setEliminatedCount(stat.getEliminatedCount());
                
                // 计算百分比
                long totalEliminated = stats.getTotalEliminatedCount();
                if (totalEliminated > 0) {
                    personalStat.setPercentage((double) stat.getEliminatedCount().longValue() / totalEliminated * 100);
                } else {
                    personalStat.setPercentage(0.0);
                }
                
                if (stat.getLastEliminated() != null) {
                    personalStat.setLastEliminatedTime(stat.getLastEliminated().toInstant()
                        .atZone(ZoneId.systemDefault()).toLocalDateTime());
                }
                
                return personalStat;
            })
            .collect(Collectors.toList());
            
        stats.setTopEmojiStats(topEmojiStats);
    }
    
    /**
     * 填充近期游戏记录
     */
    private void populateRecentGameRecords(UserGameStats stats, Long userId, String gameCode) {
        RelaxUserGameRecordBo queryBo = new RelaxUserGameRecordBo();
        queryBo.setUserId(userId);
        queryBo.setGameCode(gameCode);
        
        List<RelaxUserGameRecordVo> allRecords = relaxUserGameRecordService.queryList(queryBo);
        
        // 按创建时间倒序排序，取最近10条
        List<UserGameStats.RecentGameRecord> recentRecords = allRecords.stream()
            .sorted((a, b) -> {
                if (a.getCreateTime() == null && b.getCreateTime() == null) return 0;
                if (a.getCreateTime() == null) return 1;
                if (b.getCreateTime() == null) return -1;
                return b.getCreateTime().compareTo(a.getCreateTime());
            })
            .limit(10)
            .map(record -> {
                UserGameStats.RecentGameRecord recentRecord = new UserGameStats.RecentGameRecord();
                recentRecord.setRecordId(record.getRecordId());
                recentRecord.setScore(record.getScore());
                recentRecord.setPlayTime(record.getPlayTime() != null ? record.getPlayTime() : 0L);
                recentRecord.setEliminatedCount(record.getEliminatedCount() != null ? record.getEliminatedCount() : 0L);
                recentRecord.setGameResult(record.getGameResult());
                
                if (record.getCreateTime() != null) {
                    recentRecord.setGameTime(record.getCreateTime().toInstant()
                        .atZone(ZoneId.systemDefault()).toLocalDateTime());
                }
                
                return recentRecord;
            })
            .collect(Collectors.toList());
            
        stats.setRecentRecords(recentRecords);
    }
    
    @Override
    public GlobalGameStats getGlobalGameStats(String gameCode) {
        GlobalGameStats stats = new GlobalGameStats();
        stats.setGameCode(gameCode);
        stats.setLastUpdateTime(LocalDateTime.now());
        
        try {
            // 查询基本全局统计数据
            populateGlobalBasicStats(stats, gameCode);
            
            // 查询热门emoji统计
            populatePopularEmojis(stats, gameCode);
            
            // 查询游戏结果分布
            populateGameResultDistribution(stats, gameCode);
            
            // 查询分数段分布
            populateScoreDistribution(stats, gameCode);
            
        } catch (Exception e) {
            System.err.println("查询全局游戏统计失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        return stats;
    }
    
    /**
     * 填充全局基本统计数据
     */
    private void populateGlobalBasicStats(GlobalGameStats stats, String gameCode) {
        RelaxUserGameRecordBo queryBo = new RelaxUserGameRecordBo();
        queryBo.setGameCode(gameCode);
        
        List<RelaxUserGameRecordVo> allRecords = relaxUserGameRecordService.queryList(queryBo);
        
        if (allRecords.isEmpty()) {
            // 设置默认值
            stats.setTotalUsers(0);
            stats.setTodayActiveUsers(0);
            stats.setTotalPlayCount(0);
            stats.setTodayPlayCount(0);
            stats.setGlobalBestScore(0L);
            stats.setGlobalBestScoreUser("暂无");
            stats.setTotalScore(0L);
            stats.setGlobalAvgScore(0.0);
            stats.setTotalPlayTimeHours(0);
            stats.setTotalEliminatedCount(0L);
            stats.setTodayEliminatedCount(0L);
            return;
        }
        
        // 计算基本统计数据
        Set<Long> uniqueUsers = new HashSet<>();
        Set<Long> todayActiveUsers = new HashSet<>();
        LocalDate today = LocalDate.now();
        
        long totalScore = 0;
        long totalPlayTime = 0;
        long totalEliminated = 0;
        long todayEliminated = 0;
        long globalBestScore = 0;
        String globalBestScoreUser = "暂无";
        int todayPlayCount = 0;
        
        for (RelaxUserGameRecordVo record : allRecords) {
            // 记录用户
            uniqueUsers.add(record.getUserId());
            
            // 检查是否今日活跃
            if (record.getCreateTime() != null) {
                LocalDate playDate = record.getCreateTime().toInstant()
                    .atZone(ZoneId.systemDefault()).toLocalDate();
                if (playDate.equals(today)) {
                    todayActiveUsers.add(record.getUserId());
                    todayPlayCount++;
                    
                    if (record.getEliminatedCount() != null) {
                        todayEliminated += record.getEliminatedCount();
                    }
                }
            }
            
            // 累计数据
            if (record.getScore() != null) {
                totalScore += record.getScore();
                if (record.getScore() > globalBestScore) {
                    globalBestScore = record.getScore();
                    // 这里简化处理，实际项目中可能需要关联用户表获取用户名
                    globalBestScoreUser = "用户" + record.getUserId();
                }
            }
            
            if (record.getPlayTime() != null) {
                totalPlayTime += record.getPlayTime();
            }
            
            if (record.getEliminatedCount() != null) {
                totalEliminated += record.getEliminatedCount();
            }
        }
        
        // 设置统计结果
        stats.setTotalUsers(uniqueUsers.size());
        stats.setTodayActiveUsers(todayActiveUsers.size());
        stats.setTotalPlayCount(allRecords.size());
        stats.setTodayPlayCount(todayPlayCount);
        stats.setGlobalBestScore(globalBestScore);
        stats.setGlobalBestScoreUser(globalBestScoreUser);
        stats.setTotalScore(totalScore);
        stats.setGlobalAvgScore(allRecords.size() > 0 ? (double) totalScore / allRecords.size() : 0.0);
        stats.setTotalPlayTimeHours((int) (totalPlayTime / 3600)); // 转换为小时
        stats.setTotalEliminatedCount(totalEliminated);
        stats.setTodayEliminatedCount(todayEliminated);
    }
    
    /**
     * 填充热门emoji统计
     */
    private void populatePopularEmojis(GlobalGameStats stats, String gameCode) {
        RelaxEmojiStatisticsBo queryBo = new RelaxEmojiStatisticsBo();
        
        List<RelaxEmojiStatisticsVo> allEmojiStats = relaxEmojiStatisticsService.queryList(queryBo);
        
        // 按emoji分组并计算总消灭次数
        Map<String, GlobalGameStats.PopularEmoji> emojiMap = new HashMap<>();
        long tempTotalEliminatedCount = 0;
        
        for (RelaxEmojiStatisticsVo stat : allEmojiStats) {
            String emojiChar = stat.getEmojiChar();
            tempTotalEliminatedCount += stat.getEliminatedCount();
            
            GlobalGameStats.PopularEmoji popularEmoji = emojiMap.computeIfAbsent(emojiChar, k -> {
                GlobalGameStats.PopularEmoji emoji = new GlobalGameStats.PopularEmoji();
                emoji.setEmojiChar(emojiChar);
                emoji.setEliminatedCount(0L);
                emoji.setUserCount(0);
                return emoji;
            });
            
            popularEmoji.setEliminatedCount(popularEmoji.getEliminatedCount() + stat.getEliminatedCount());
            popularEmoji.setUserCount(popularEmoji.getUserCount() + 1);
        }
        
        final long totalEliminatedCount = tempTotalEliminatedCount;
        
        // 计算百分比并排序取前5名
        List<GlobalGameStats.PopularEmoji> popularEmojis = emojiMap.values().stream()
            .peek(emoji -> {
                if (totalEliminatedCount > 0) {
                    emoji.setPercentage((double) emoji.getEliminatedCount().longValue() / totalEliminatedCount * 100);
                } else {
                    emoji.setPercentage(0.0);
                }
            })
            .sorted((a, b) -> Long.compare(b.getEliminatedCount(), a.getEliminatedCount()))
            .limit(5)
            .collect(Collectors.toList());
            
        stats.setPopularEmojis(popularEmojis);
    }
    
    /**
     * 填充游戏结果分布
     */
    private void populateGameResultDistribution(GlobalGameStats stats, String gameCode) {
        RelaxUserGameRecordBo queryBo = new RelaxUserGameRecordBo();
        queryBo.setGameCode(gameCode);
        
        List<RelaxUserGameRecordVo> allRecords = relaxUserGameRecordService.queryList(queryBo);
        
        int completedCount = 0;
        int timeoutCount = 0;
        int quitCount = 0;
        
        for (RelaxUserGameRecordVo record : allRecords) {
            String gameResult = record.getGameResult();
            if ("completed".equals(gameResult)) {
                completedCount++;
            } else if ("timeout".equals(gameResult)) {
                timeoutCount++;
            } else if ("quit".equals(gameResult)) {
                quitCount++;
            }
        }
        
        GlobalGameStats.GameResultDistribution distribution = new GlobalGameStats.GameResultDistribution();
        distribution.setCompletedCount(completedCount);
        distribution.setTimeoutCount(timeoutCount);
        distribution.setQuitCount(quitCount);
        
        int totalGames = allRecords.size();
        if (totalGames > 0) {
            distribution.setCompletionRate((double) completedCount / totalGames * 100);
        } else {
            distribution.setCompletionRate(0.0);
        }
        
        stats.setResultDistribution(distribution);
    }
    
    /**
     * 填充分数段分布
     */
    private void populateScoreDistribution(GlobalGameStats stats, String gameCode) {
        RelaxUserGameRecordBo queryBo = new RelaxUserGameRecordBo();
        queryBo.setGameCode(gameCode);
        
        List<RelaxUserGameRecordVo> allRecords = relaxUserGameRecordService.queryList(queryBo);
        
        // 定义分数段
        Map<String, Integer> scoreRanges = new HashMap<>();
        scoreRanges.put("0-100", 0);
        scoreRanges.put("101-300", 0);
        scoreRanges.put("301-500", 0);
        scoreRanges.put("501-1000", 0);
        scoreRanges.put("1000+", 0);
        
        for (RelaxUserGameRecordVo record : allRecords) {
            if (record.getScore() != null) {
                long score = record.getScore();
                if (score <= 100) {
                    scoreRanges.put("0-100", scoreRanges.get("0-100") + 1);
                } else if (score <= 300) {
                    scoreRanges.put("101-300", scoreRanges.get("101-300") + 1);
                } else if (score <= 500) {
                    scoreRanges.put("301-500", scoreRanges.get("301-500") + 1);
                } else if (score <= 1000) {
                    scoreRanges.put("501-1000", scoreRanges.get("501-1000") + 1);
                } else {
                    scoreRanges.put("1000+", scoreRanges.get("1000+") + 1);
                }
            }
        }
        
        int totalGames = allRecords.size();
        List<GlobalGameStats.ScoreDistribution> distributions = scoreRanges.entrySet().stream()
            .map(entry -> {
                GlobalGameStats.ScoreDistribution distribution = new GlobalGameStats.ScoreDistribution();
                distribution.setScoreRange(entry.getKey());
                distribution.setPlayCount(entry.getValue());
                
                if (totalGames > 0) {
                    distribution.setPercentage((double) entry.getValue() / totalGames * 100);
                } else {
                    distribution.setPercentage(0.0);
                }
                
                return distribution;
            })
            .collect(Collectors.toList());
            
        stats.setScoreDistributions(distributions);
    }
    
    @Override
    public List<EmojiRankingItem> getEmojiRanking(String gameCode, Integer limit) {
        try {
            // 查询所有emoji统计数据
            RelaxEmojiStatisticsBo queryBo = new RelaxEmojiStatisticsBo();
            List<RelaxEmojiStatisticsVo> allEmojiStats = relaxEmojiStatisticsService.queryList(queryBo);
            
            if (allEmojiStats.isEmpty()) {
                return List.of();
            }
            
            // 按emoji分组并计算总消灭次数和用户数
            Map<String, EmojiRankingData> emojiMap = new HashMap<>();
            long globalTotalEliminated = 0;
            
            for (RelaxEmojiStatisticsVo stat : allEmojiStats) {
                String emojiChar = stat.getEmojiChar();
                globalTotalEliminated += stat.getEliminatedCount();
                
                EmojiRankingData rankingData = emojiMap.computeIfAbsent(emojiChar, k -> {
                    EmojiRankingData data = new EmojiRankingData();
                    data.emojiChar = emojiChar;
                    data.emojiUnicode = stat.getEmojiUnicode();
                    data.totalEliminatedCount = 0L;
                    data.userCount = 0;
                    data.firstEliminatedTime = null;
                    data.lastEliminatedTime = null;
                    return data;
                });
                
                rankingData.totalEliminatedCount += stat.getEliminatedCount();
                rankingData.userCount++;
                
                // 记录最早和最晚消灭时间
                if (stat.getFirstEliminated() != null) {
                    if (rankingData.firstEliminatedTime == null || 
                        stat.getFirstEliminated().before(rankingData.firstEliminatedTime)) {
                        rankingData.firstEliminatedTime = stat.getFirstEliminated();
                    }
                }
                
                if (stat.getLastEliminated() != null) {
                    if (rankingData.lastEliminatedTime == null || 
                        stat.getLastEliminated().after(rankingData.lastEliminatedTime)) {
                        rankingData.lastEliminatedTime = stat.getLastEliminated();
                    }
                }
            }
            
            // 转换为排行榜项目并排序
            final long totalEliminated = globalTotalEliminated;
            List<EmojiRankingItem> rankingList = emojiMap.values().stream()
                .map(data -> {
                    EmojiRankingItem item = new EmojiRankingItem();
                    item.setEmojiChar(data.emojiChar);
                    item.setEmojiUnicode(data.emojiUnicode);
                    item.setTotalEliminatedCount(data.totalEliminatedCount);
                    item.setUserCount(data.userCount);
                    
                    // 计算全局占比
                    if (totalEliminated > 0) {
                        item.setPercentage((double) data.totalEliminatedCount.longValue() / totalEliminated * 100);
                    } else {
                        item.setPercentage(0.0);
                    }
                    
                    // 计算平均每用户消灭数
                    if (data.userCount > 0) {
                        item.setAvgPerUser((double) data.totalEliminatedCount.longValue() / data.userCount);
                    } else {
                        item.setAvgPerUser(0.0);
                    }
                    
                    // 设置时间信息
                    if (data.firstEliminatedTime != null) {
                        item.setFirstEliminatedTime(data.firstEliminatedTime.toInstant()
                            .atZone(ZoneId.systemDefault()).toLocalDateTime());
                    }
                    if (data.lastEliminatedTime != null) {
                        item.setLastEliminatedTime(data.lastEliminatedTime.toInstant()
                            .atZone(ZoneId.systemDefault()).toLocalDateTime());
                    }
                    
                    return item;
                })
                .sorted((a, b) -> Long.compare(b.getTotalEliminatedCount(), a.getTotalEliminatedCount()))
                .collect(Collectors.toList());
            
            // 设置排名
            for (int i = 0; i < rankingList.size(); i++) {
                rankingList.get(i).setRank(i + 1);
            }
            
            // 限制返回数量
            if (limit != null && limit > 0 && rankingList.size() > limit) {
                rankingList = rankingList.subList(0, limit);
            }
            
            return rankingList;
            
        } catch (Exception e) {
            System.err.println("查询Emoji排行榜失败: " + e.getMessage());
            e.printStackTrace();
            return List.of();
        }
    }
    
    /**
     * emoji排行榜数据临时类
     */
    private static class EmojiRankingData {
        String emojiChar;
        String emojiUnicode;
        Long totalEliminatedCount;
        Integer userCount;
        Date firstEliminatedTime;
        Date lastEliminatedTime;
    }
    
    /**
     * 批量保存游戏数据（优化性能）
     */
    private void batchSaveGameData(Long recordId, Long userId, String gameCode, 
                                  List<GameFinishData.EmojiEliminateDetail> emojiDetails) {
        // 批量保存游戏记录详情
        batchSaveGameRecordDetails(recordId, userId, gameCode, emojiDetails);
        
        // 聚合emoji统计数据并批量更新
        batchUpdateEmojiStatistics(userId, emojiDetails);
    }
    
    /**
     * 批量保存游戏记录详情
     */
    private void batchSaveGameRecordDetails(Long recordId, Long userId, String gameCode,
                                          List<GameFinishData.EmojiEliminateDetail> emojiDetails) {
        List<RelaxGameRecordDetailBo> detailBoList = new ArrayList<>();
        
        for (GameFinishData.EmojiEliminateDetail detail : emojiDetails) {
            RelaxGameRecordDetailBo detailBo = new RelaxGameRecordDetailBo();
            detailBo.setRecordId(recordId);
            detailBo.setUserId(userId);
            detailBo.setGameCode(gameCode);
            detailBo.setEmojiUnicode(detail.getEmojiUnicode());
            detailBo.setEmojiChar(detail.getEmojiChar());
            detailBo.setEliminatedCount(detail.getEliminatedCount());
            
            // 设置消灭时间（使用最后消灭时间）
            if (detail.getLastEliminatedTime() != null) {
                detailBo.setEliminatedTime(new Date(detail.getLastEliminatedTime()));
            }
            
            detailBoList.add(detailBo);
        }
        
        // 如果支持批量插入，使用批量插入；否则逐个插入
        for (RelaxGameRecordDetailBo detailBo : detailBoList) {
            relaxGameRecordDetailService.insertByBo(detailBo);
        }
    }
    
    /**
     * 批量更新emoji统计数据（聚合处理，减少数据库查询）
     */
    private void batchUpdateEmojiStatistics(Long userId, List<GameFinishData.EmojiEliminateDetail> emojiDetails) {
        // 聚合相同emoji的数据
        Map<String, GameFinishData.EmojiEliminateDetail> aggregatedData = new HashMap<>();
        
        for (GameFinishData.EmojiEliminateDetail detail : emojiDetails) {
            String emojiUnicode = detail.getEmojiUnicode();
            if (aggregatedData.containsKey(emojiUnicode)) {
                // 合并数据
                GameFinishData.EmojiEliminateDetail existing = aggregatedData.get(emojiUnicode);
                existing.setEliminatedCount(existing.getEliminatedCount() + detail.getEliminatedCount());
                
                // 更新最早和最晚时间
                if (detail.getFirstEliminatedTime() != null && 
                    (existing.getFirstEliminatedTime() == null || detail.getFirstEliminatedTime() < existing.getFirstEliminatedTime())) {
                    existing.setFirstEliminatedTime(detail.getFirstEliminatedTime());
                }
                if (detail.getLastEliminatedTime() != null &&
                    (existing.getLastEliminatedTime() == null || detail.getLastEliminatedTime() > existing.getLastEliminatedTime())) {
                    existing.setLastEliminatedTime(detail.getLastEliminatedTime());
                }
            } else {
                aggregatedData.put(emojiUnicode, detail);
            }
        }
        
        // 批量查询现有的统计记录
        List<String> emojiUnicodes = new ArrayList<>(aggregatedData.keySet());
        Map<String, RelaxEmojiStatisticsVo> existingStatsMap = batchQueryEmojiStatistics(userId, emojiUnicodes);
        
        // 分别处理新增和更新
        List<RelaxEmojiStatisticsBo> toInsert = new ArrayList<>();
        List<RelaxEmojiStatisticsBo> toUpdate = new ArrayList<>();
        
        for (Map.Entry<String, GameFinishData.EmojiEliminateDetail> entry : aggregatedData.entrySet()) {
            String emojiUnicode = entry.getKey();
            GameFinishData.EmojiEliminateDetail detail = entry.getValue();
            
            if (existingStatsMap.containsKey(emojiUnicode)) {
                // 更新现有记录
                RelaxEmojiStatisticsVo existingStat = existingStatsMap.get(emojiUnicode);
                RelaxEmojiStatisticsBo updateBo = new RelaxEmojiStatisticsBo();
                updateBo.setStatId(existingStat.getStatId());
                updateBo.setEliminatedCount(existingStat.getEliminatedCount() + detail.getEliminatedCount());
                
                if (detail.getLastEliminatedTime() != null) {
                    updateBo.setLastEliminated(new Date(detail.getLastEliminatedTime()));
                }
                
                toUpdate.add(updateBo);
            } else {
                // 新增记录
                RelaxEmojiStatisticsBo insertBo = new RelaxEmojiStatisticsBo();
                insertBo.setUserId(userId);
                insertBo.setEmojiUnicode(detail.getEmojiUnicode());
                insertBo.setEmojiChar(detail.getEmojiChar());
                insertBo.setEliminatedCount(detail.getEliminatedCount());
                
                if (detail.getFirstEliminatedTime() != null) {
                    insertBo.setFirstEliminated(new Date(detail.getFirstEliminatedTime()));
                }
                if (detail.getLastEliminatedTime() != null) {
                    insertBo.setLastEliminated(new Date(detail.getLastEliminatedTime()));
                }
                
                toInsert.add(insertBo);
            }
        }
        
        // 执行批量操作
        for (RelaxEmojiStatisticsBo insertBo : toInsert) {
            relaxEmojiStatisticsService.insertByBo(insertBo);
        }
        for (RelaxEmojiStatisticsBo updateBo : toUpdate) {
            relaxEmojiStatisticsService.updateByBo(updateBo);
        }
    }
    
    /**
     * 批量查询emoji统计数据
     */
    private Map<String, RelaxEmojiStatisticsVo> batchQueryEmojiStatistics(Long userId, List<String> emojiUnicodes) {
        Map<String, RelaxEmojiStatisticsVo> result = new HashMap<>();
        
        // 为每个emoji单独查询（后续可以优化为IN查询）
        for (String emojiUnicode : emojiUnicodes) {
            RelaxEmojiStatisticsBo queryBo = new RelaxEmojiStatisticsBo();
            queryBo.setUserId(userId);
            queryBo.setEmojiUnicode(emojiUnicode);
            
            List<RelaxEmojiStatisticsVo> existingStats = relaxEmojiStatisticsService.queryList(queryBo);
            if (!existingStats.isEmpty()) {
                result.put(emojiUnicode, existingStats.get(0));
            }
        }
        
        return result;
    }
}